import { Component, OnInit, OnChanges, Input, Output, EventEmitter } from '@angular/core';
import { _HttpClient } from '@delon/theme';

import { FormControl, FormBuilder, FormGroup, Validators } from '@angular/forms';

import { NzMessageService, UploadFile } from 'ng-zorro-antd';
import { Observable, Observer } from 'rxjs';

import { SkWebService } from '@service/skweb.service';
import { CommonUtil } from '@utils/common.util';

@Component({
  selector: 'app-appdetail',
  templateUrl: './appdetail.component.html',
  styleUrls: ['./appdetail.component.less'],
})
export class AppDetailComponent implements OnInit, OnChanges {
  @Input() public appInfo: any;
  @Input() public operate: string;
  // tslint:disable-next-line:no-output-on-prefix
  @Output() public onRefreshData = new EventEmitter<any>();

  public appPreviewIcon;  // app预览图标
  public fileObj: UploadFile; // app图标文件数据
  public validateForm: FormGroup;  // 表单验证
  public formErrorDesc: any = {};  // 各类错误的描述
  public loading = false;
  // public appTypeLoading = false;  // appType加载状态
  public appTypeList: any[] = [];
  public isShowMore = false;  // 展开更多

  constructor(
    private fb: FormBuilder,
    private skWebService: SkWebService,
    private nzMsg: NzMessageService
  ) { }

  public ngOnInit() {
    // 初始化表单的值以及验证规则
    this.validateForm = this.fb.group({
      appName: [null, this.appNameValidator],
      appType: [null, Validators.required],
      appUrl: [null, Validators.required],
      platform: [''],
      seqNum: [1, this.seqNumValidator],
      forWalletVersion: [null],
      appCode: [null],
      chatDapp: ['false'],  // 不转string无效
      uiOptions: [null, this.uiOptionsValidator]
    });
    this.loadAppType();
  }

  public ngOnChanges() {
    // 判断this.validateForm是否初始化, 因为ngOnChanges第一次是在ngOnInit前调用的
    if (!this.validateForm) {
      return;
    }
    // 根据父组件传入的appInfo更新from绑定的数据
    const {
      appIcon, appName, appType, appUrl, seqNum = 1, platform = '', forWalletVersion, appCode, chatDapp = false, uiOptions
    } = this.appInfo;

    this.appPreviewIcon = appIcon;
    this.validateForm.reset(); // 初始化话重置
    this.validateForm.get('appName').setValue(appName);
    this.validateForm.get('appType').setValue(appType);
    this.validateForm.get('appUrl').setValue(appUrl);
    this.validateForm.get('platform').setValue(platform);
    this.validateForm.get('seqNum').setValue(seqNum);
    this.validateForm.get('forWalletVersion').setValue(forWalletVersion);
    this.validateForm.get('appCode').setValue(appCode);
    this.validateForm.get('chatDapp').setValue(chatDapp.toString());
    this.validateForm.get('uiOptions').setValue(uiOptions ? JSON.stringify(uiOptions) : null);
  }

  // app名称检测规则
  public appNameValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      this.formErrorDesc['appName'] = 'app名称不可为空';
      return { error: true };
    }
  }

  // 自定义属性检测规则
  public uiOptionsValidator = (control: FormControl): { [s: string]: boolean } => {
    if (control.value) {
      if (!CommonUtil.isJSON(control.value)) {
        return { error: true };
      }
    }
  }

  // 发布顺序检测规则
  public seqNumValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!(/(^[1-9]\d*$)/.test(control.value))) {
      return { error: true };
    }
  }

  // app图标预览
  public uploadPreview = (file: UploadFile): boolean => {
    if (file.name.endsWith('.png')) {
      this.appPreviewIcon = window.URL.createObjectURL(file);  // 图片预览链接
      this.fileObj = file;
    } else {
      this.nzMsg.error('请上传png格式的图片');
    }
    return false;
  }

  // 获取app类型集合(扩展)
  public loadAppType() {
    this.appTypeList = [
      { label: '行情', value: 'marketAppList'},
      { label: '新品', value: 'gameNewAppList' },
      { label: '热门', value: 'gameHotAppList' },
      { label: '群组', value: 'hotTgGroup' },
      { label: '工具', value: 'toolsAppList' }
    ];
    // this.appTypeLoading = true;
    // const ret: any = await this.skWebService.distinctAppType();
    // this.appTypeLoading = false;
    // if (ret && ret.errcode === 0) {
    //   this.appTypeList = ret.data;
    // }
  }

  // 添加app类型
  public async increateAppType(newAppType) {
    if (newAppType) {
      this.appTypeList.unshift(newAppType.trim());
      this.validateForm.get('appType').setValue(newAppType.trim());
    }
  }

  // 提交app信息
  public async submitDetail() {
    // tslint:disable-next-line:forin
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    // 表单验证无效, 是否有图标预览图
    if (this.validateForm.status === 'INVALID' || !this.appPreviewIcon) {
      return;
    }
    this.loading = true;
    this.appInfo['appName'] = this.validateForm.get('appName').value;
    this.appInfo['appType'] = this.validateForm.get('appType').value;
    this.appInfo['appUrl'] = this.validateForm.get('appUrl').value;
    this.appInfo['platform'] = this.validateForm.get('platform').value;
    this.appInfo['seqNum'] = this.validateForm.get('seqNum').value;
    this.appInfo['forWalletVersion'] = this.validateForm.get('forWalletVersion').value;
    this.appInfo['appCode'] = this.validateForm.get('appCode').value;
    this.appInfo['chatDapp'] = this.validateForm.get('chatDapp').value;
    this.appInfo['uiOptions'] = this.validateForm.get('uiOptions').value;

    // 判断是否有重新上传图标文件
    if (this.fileObj) {
      const uploadRet: any = await this.skWebService.uploadFile([this.fileObj], 'dapp');
      if (uploadRet && uploadRet.errcode === 0) {
        // 获取app图标的链接
        this.appInfo.appIcon = uploadRet.data.path;
      }
    }

    // 更新app信息
    const ret = await this.skWebService.upsertThirdPartyApp(this.operate, this.appInfo);
    if (ret && ret.errcode === 0) {
      this.onRefreshData.emit(); // 通知父组件刷新数据
      this.fileObj = null; // 清空文件数据
    }
    this.loading = false;
  }

  public showMore() {
    this.isShowMore = !this.isShowMore;
  }
}
